package com.lsu.app.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsu.app.bean.ClickDate;
import com.lsu.app.service.ClickDateService;
import com.lsu.app.mapper.ClickDateMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @description 针对表【click_date(课程点击量)】的数据库操作Service实现
 * @Date 2023-11-14 20:26:04
 * @author hjj
 */
@Transactional
@Service
public class ClickDateServiceImpl extends ServiceImpl<ClickDateMapper, ClickDate> implements ClickDateService{
        private final ClickDateMapper mapper;

    public ClickDateServiceImpl(ClickDateMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void updateClickNumById(Integer courseId) {
        Integer id = mapper.getIdByCourseIdAndDate(courseId, LocalDate.now().toString());
        Integer teacherId = mapper.getTeacherIdByCourseId(courseId);
        if(id==null){
            mapper.insert(new ClickDate(courseId,LocalDate.now().toString(),teacherId));
        }else{
            mapper.updateClickNumById(id);
        }
    }

    @Override
    public Integer[] getClicksByDays(Integer days,Integer teacherId) {

        Integer[] nums = new Integer[days];
        LocalDate now = LocalDate.now();
        for(int i=1;i<=days;i++){
            Integer num = mapper.getClickByDate(teacherId,now.plusDays(-i).toString());
            if(num!=null){
                nums[i-1]=num;
            }else{
                nums[i-1]=0;
            }
        }
        return nums;
    }

    @Override
    public String getRate(Integer teacherId) {
        LocalDate now = LocalDate.now();
        DecimalFormat df = new DecimalFormat("#.#");
        Integer day1 = mapper.getClickByDate(teacherId,now.plusDays(-1).toString());
        Integer day2 = mapper.getClickByDate(teacherId,now.plusDays(-2).toString());
        if(day2==null||day1==null||day2==0||day1==0){
            return "0";
        }
        return df.format( ((double)day1/(double)day2)-1);
    }

    @Override
    public Integer getClickNumOfCourseTalk(Integer courseId) {
        Integer sum = mapper.getClickNumOfCourseTalk(courseId);
        return sum==null?0:sum;
    }

}




